'use strict'

const path = require('path')
const fs = require('fs')
const fse = require('fs-extra')
const Command = require('@kpzc-cli-dev/command')
const Git = require('@kpzc-cli-dev/git')
const log = require('@kpzc-cli-dev/log')

class PublishCommand extends Command {
  init() {
    log.verbose('publish', this._argv)
    this.options = {
      refershServer: this._argv[0].refershServer,
      refershToken: this._argv[0].refershToken,
      refershOwner: this._argv[0].refershOwner,
      buildCmd: this._argv[0].buildCmd,
      prod: this._argv[0].prod,
      sshUser: this._argv[0].sshUser,
      sshIp: this._argv[0].sshIp,
      sshPath: this._argv[0].sshPath
    }
  }
  async exec() {
    try {
      // 1. 初始化检查
      this.prepare()
      // 2. Git Flow 自动化
      const git = new Git(this.projectInfo, this.options)
      await git.prepare() // 自动化提交的准备和代码仓库初始化
      await git.commit() // 代码自动化提交
      await git.publish() // 代码云构建+云发布
      // 3. 云构建和云发布
      const startTime = new Date().getTime()
      const endTime = new Date().getTime()
      log.info(
        '本次发布耗时：',
        Math.floor((endTime - startTime) / 1000) + '秒'
      )
    } catch (e) {
      log.error(e.message)
      if (process.env.LOG_LEVEL === 'verbose') {
        console.log(e)
      }
    }
  }
  prepare() {
    // 1. 确认项目是否是npm项目
    const projectPath = process.cwd()
    const pkgPath = path.resolve(projectPath, 'package.json')
    log.verbose('package.json', pkgPath)
    if (!fs.existsSync(pkgPath)) {
      throw new Error('package.json不存在！')
    }
    // 2. 确认是否包含build命令
    const { name, version, scripts } = fse.readJSONSync(pkgPath)
    log.verbose('package.json', name, version, scripts)
    if (!name || !version || !scripts || !scripts.build) {
      throw new Error(
        'package.json信息不全，请检查是否存在name、version和scripts（需提供build命令）！'
      )
    }
    this.projectInfo = { name, version, dir: projectPath }
  }
}

function publish(argv) {
  log.verbose('argv', argv)
  return new PublishCommand(argv)
}

module.exports = publish
module.exports.PublishCommand = PublishCommand
